package com.sinothk.server.plus.qrcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class QrCodeCreator {

    /** 定义二维码的宽度 */
    private final static int WIDTH = 300;
    /** 定义二维码的高度 */
    private final static int HEIGHT = 300;
    /** 定义二维码的格式 */
    private final static String FORMAT = "png";

    /**
     * @param file
     * @param content
     * @return void
     * */
    public static void generateQRCode(File file, String content) {
        // 定义二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
        // 设置编码
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置边距，默认为5
        hints.put(EncodeHintType.MARGIN, 2);

        try {
            BitMatrix bitMatrix = new MultiFormatWriter()
                    .encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            Path path = file.toPath();
            // 保存到项目跟目录中
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param file    读取二维码的文件名
     * @return void
     * */
    public static Result readQRCode(File file) throws Exception {
        MultiFormatReader reader = new MultiFormatReader();

        BufferedImage image = ImageIO.read(file);
        BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
        Result result = reader.decode(binaryBitmap, hints);
        return result;
    }

//    public static void main(String[] args) throws Exception {
//        generateQRCode(new File("smt.png"), "勤思物联·SINOTHK");
//
//        Result result = readQRCode(new File("smt.png"));
//        System.out.println("解析结果: " + new String(result.toString().getBytes("GBK"), "GBK"));
//        System.out.println("二维码格式: " + result.getBarcodeFormat());
//        System.out.println("二维码文本内容: " + new String(result.getText().getBytes("GBK"), "GBK"));
//    }
}
